package com.yuandian.ops.workbench.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.business_monitor.feign.RemoteAlarmMergingQueryService;
import com.yuandian.api.business_monitor.po.AlarmParams;
import com.yuandian.api.business_monitor.vo.AlarmProportionCopyVo;
import com.yuandian.api.business_monitor.vo.AlarmProportionVo;
import com.yuandian.api.management.feign.RemoteAlarmIndicatorsService;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.constant.Constants;
import com.yuandian.ops.workbench.mapper.BusinessAlarmMapper;
import com.yuandian.ops.workbench.service.IBusinessAlarmService;
import com.yuandian.ops.workbench.vo.BusiDetailExcelVo;
import com.yuandian.ops.workbench.vo.BusiDetailStatAlarmVo;
import com.yuandian.utils.BeanUtils;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 告警业务查询
 *
 * @author LinShiHe
 * @date 2023/03/12
 */
@Slf4j
@Service
public class BusinessAlarmServiceImpl implements IBusinessAlarmService {

	@Autowired
	private RemoteAlarmMergingQueryService busiAlarmService;

    @Autowired
    private BusinessAlarmMapper businessAlarmMapper;
	@Autowired
	private RemoteAlarmIndicatorsService remoteAlarmIndicatorsService;
/*
    @Autowired
    private ISearchOptionService searchOptionService;

    @Autowired
    private BusiAlarmService busiAlarmService;

    @Autowired
    private DocumentExportController exportController;*/

    /**
     * 查询告警业务信息
     *
     * @param params
     * @return 通用返回对象
     */
    @Override
    public R<Object> getBusinessAlarm(AlarmParams params) {


        // 4、设置分页对象，如果不传pageNum或pageSize，相当于不分页
        Page<BusiDetailStatAlarmVo> page = null;
        if (params.getPageNum() > 0) {
            page = new Page<>(params.getPageNum(), params.getPageSize());
        }
        //设置告警类型集合
        if (params != null && (params.getAlarmTypeIds() == null || params.getAlarmTypeIds().size() < 1)) {
            List<Integer> typeList = new ArrayList<Integer>();
            typeList.add(0);
            params.setAlarmTypeIds(typeList);
        }
        // 去掉前后空格
        if (params != null && StringUtils.isNotBlank(params.getBusinessName())) {
            params.setBusinessName(params.getBusinessName().trim());
        }
        //5.查询数据
        List<BusiDetailStatAlarmVo> list = businessAlarmMapper.queryBusiDetail(page, params, "ads_busi_detail_alarm_stat_m");
        // 6、返回分页对象
        if (page == null) {
            return R.ok(new PageDataInfo(list.size(), list));
        }
        return R.ok(new PageDataInfo(page, list));
    }


    /**
     * 告警业务查询下载
     *
     * @param params
     * @param response
     * @return 通用返回对象
     */
    @Override
    public void exportExcel(AlarmParams params, HttpServletResponse response) throws IOException {
        //设置告警类型集合
        if (params != null && (params.getAlarmTypeIds() == null || params.getAlarmTypeIds().size() < 1)) {
            List<Integer> typeList = new ArrayList<Integer>();
            typeList.add(0);
            params.setAlarmTypeIds(typeList);
        }
        // 去掉前后空格
        if (params != null && StringUtils.isNotBlank(params.getBusinessName())) {
            params.setBusinessName(params.getBusinessName().trim());
        }

        //查询数据
        List<BusiDetailExcelVo> list = businessAlarmMapper.queryBusiDetailExcel(params, "ads_busi_detail_alarm_stat_m");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String folder = Constants.EXPORT_PATH + File.separator + sdf.format(date) + File.separator;

        String fileName = "busiDetailAlarm_" + System.currentTimeMillis() + ".xlsx";
        String filePath = folder + fileName;
        int number = 1;
        for (BusiDetailExcelVo busiDetailExcelVo : list) {
            busiDetailExcelVo.setNumber(number++);
        }
        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号", "业务名称", "访问量", "完整访问量", "平均办理时长", "失败访问量", "告警访问量","成功率", "健康率");
        String title = "告警业务列表";
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        titleParams.add(params.getSystemName());
        //当告警类型有且只有一条时才展示
        if (params.getAlarmTypeIds() != null && params.getAlarmTypeIds().size() == 1){
            titleParams.add(remoteAlarmIndicatorsService.queryById(params.getAlarmTypeId()).getData().getName());
        }
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams, params.getStartTime(), params.getEndTime());
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });

        ExcelUtil.writeExcel(BusiDetailExcelVo.class, filePath, title, list, headList, response);
    }

	/**
	 * 告警归并分析下载接口
	 * @param params
	 * @param response
	 */
	@Override
	public void getAlarmMergeDownLoad(AlarmParams params, HttpServletResponse response) throws UnsupportedEncodingException {
		params.setPageNum(1);
		params.setPageSize(-1);
		PageDataInfo info = BeanUtils
				.cast(busiAlarmService.getBusinessGradeDate(params).getData());
		List<AlarmProportionVo> alarmOverviewList = BeanUtil.copyToList(info.getData(), AlarmProportionVo.class);
		int number = 1;
		for (AlarmProportionVo alarmProportionVo : alarmOverviewList) {
			alarmProportionVo.setNumber(number++);
		}

		response.reset();
		response.setContentType("application/vnd.ms-excel");
		String fileName = URLEncoder.encode("ht", "utf-8").replaceAll("\\+", "%20");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
		ExcelWriter excelWriter = null;
		try {
			excelWriter  = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))
					.registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 30, (short) 20)).build();
			// 去调用写入,这里我调用了五次，实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面

			// 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。这里注意DemoData.class 可以每次都变，我这里为了方便 所以用的同一个class
			// 实际上可以一直变
			WriteSheet writeSheet =
					EasyExcel.writerSheet(0, "告警总览" )
					.head(AlarmProportionVo.class)
					.registerWriteHandler(ExcelUtil.defaultStyle)
					.build();

			// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
			excelWriter.write(alarmOverviewList, writeSheet);

			for (int i = 0; i < alarmOverviewList.size(); i++) {
				params.setAlarmTypeId(alarmOverviewList.get(i).getAlarmTypeId());
				params.setSystemId(alarmOverviewList.get(i).getSystemId());
				PageDataInfo dataInfo = BeanUtils.cast(busiAlarmService.getBusinessAlarmList(params).getData());
				List<AlarmProportionCopyVo> alarmDetailList = BeanUtil.copyToList(dataInfo.getData(), AlarmProportionCopyVo.class);
				int num = 1;
				for (AlarmProportionCopyVo alarmProportionCopyVo : alarmDetailList) {
					alarmProportionCopyVo.setNumber(num ++);
				}
				List<List<String>> head = new ArrayList<>();
				String[] secondHead = {"序号","", "告警等级", "告警次数","系统名称","网端名称", "业务名称", "步骤名称", "资源识别串", "告警开始时间","告警结束时间"};
				secondHead[1] = alarmOverviewList.get(i).getAlarmTypeName();
				for (String s : secondHead) {
					List<String> header = new ArrayList<>();
					header.add(alarmOverviewList.get(i).getAlarmTypeName() + "告警详情");
					header.add(s);
					head.add(header);
				}
				WriteSheet writeSheet1 =
						EasyExcel.writerSheet( i + 1 , alarmOverviewList.get(i).getAlarmTypeName())
						.head(head)
						.registerWriteHandler(ExcelUtil.defaultStyle)
						.build();

				// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
				if (alarmDetailList.size() == 0) {
					alarmDetailList = new ArrayList<>();
				}
				excelWriter.write(alarmDetailList, writeSheet1);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			excelWriter.finish();
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
